package com.base.controller.wx_mp_api;

import com.base.helper.WebHelper;
import com.base.po.wx.WXAccessToken;
import com.base.po.wx.WXJsSdkToken;
import com.base.utils.Redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Component
public class Wx_TokenController {

    private final RedisUtil redisUtil;

    public Wx_TokenController(RedisUtil redisUtil) {
        this.redisUtil = redisUtil;
    }

    public String getTokeFromRedis(String appId, String secret){
        String token = redisUtil.get(appId);
        if (token == null){
            Map<String, Object> tokenMap = getAccessTokenByCgiBin(appId, secret);
            String accessToken = (String)tokenMap.get("accessToken");
            if (accessToken != null){
                System.out.println("接口获取微信accessToken");
                redisUtil.set(appId, accessToken, 3600);
                return accessToken;
            }
        }
        System.out.println("redis获取微信accessToken");
        return token;
    }

    public Map<String, Object> getAccessTokenByOauth2(String appId, String secret, String code){
        Map<String, Object> map = new HashedMap();
        log.warn("[微信JSAPI]appId={} secret={} code={}",appId,secret,code);
        String tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appId + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
        try {
            String result = WebHelper.PostData(tokenUrl, null, null, null);
            log.warn("[微信JSAPI] result={}",result);
            WXAccessToken token = (WXAccessToken) JSONObject.toBean(JSONObject.fromObject(result), WXAccessToken.class);
            map.put("accessToken", token.getAccess_token());
            map.put("openId", token.getOpenid());
        }catch (Exception e){
            map = null;
        }

        return map;
    }

    public Map<String, Object> getAccessTokenByCgiBin(String appId, String secret){
        Map<String, Object> map = new HashedMap();

        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;
        try {
            String result = WebHelper.PostData(tokenUrl, null, null, null);
            System.out.println(result);
            WXJsSdkToken token = (WXJsSdkToken) JSONObject.toBean(JSONObject.fromObject(result), WXJsSdkToken.class);
            map.put("accessToken", token.getAccess_token());
        }catch (Exception e){
            map = null;
        }

        return map;
    }
}
